//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.setting;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import tv.dyndns.kishibe.client.Service;
import tv.dyndns.kishibe.client.UserData;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class PanelSettingThemeMode extends VerticalPanel implements ClickHandler {
	private static final int PLAY_COUNT_THRESHOLD = 100;
	private static final int MAX_WORD_LENGTH = 8;
	private static final int UPDATE_PERIOD = 1000;
	private final Grid grid = new Grid();
	private final TextBox textBoxTheme = new TextBox();
	private final TextBox textBoxQuery = new TextBox();
	private final Button buttonAdd = new Button("追加", this);
	private final Button buttonRemove = new Button("削除", this);
	private final Button buttonApplication = new Button("テーマモードの編集権限の申請をする(確認画面が出ます)", this);
	private final TextBox textBox = new TextBox();
	private final Timer timerUpdateForm = new Timer() {
		public void run() {
			updateForm();
		}
	};

	public PanelSettingThemeMode() {
		Service.Util.getInstance().isThemeModeEditor(UserData.getInstance().getUserCode(), callbackIsThemeModeEditor);
	}

	private final AsyncCallback<Boolean> callbackIsThemeModeEditor = new AsyncCallback<Boolean>() {
		public void onSuccess(Boolean result) {
			if (result) {
				displayEditForm();
			} else if (UserData.getInstance().getPlayCount() >= PLAY_COUNT_THRESHOLD) {
				displayHaveRight();
			} else {
				displayNoRight();
			}
		}

		public void onFailure(Throwable caught) {
		}
	};

	private void displayEditForm() {
		add(new HTML("申請有難うございました。<br><br>テーマモードのテーマの設定を行います。<br>それぞれのテーマは「テーマ」と「単語」の組み合わせでできています。<br>それぞれのテーマに設定されている単語が文章中に含まれる問題が出題されます。"));

		grid.addStyleName("gridFrame");
		add(grid);

		{
			final HorizontalPanel panel = new HorizontalPanel();
			textBoxTheme.setWidth("200px");
			textBoxTheme.setMaxLength(MAX_WORD_LENGTH);
			textBoxQuery.setWidth("200px");
			textBoxQuery.setMaxLength(MAX_WORD_LENGTH);
			panel.add(new HTML("テーマ"));
			panel.add(textBoxTheme);
			panel.add(new HTML("単語"));
			panel.add(textBoxQuery);
			panel.add(buttonAdd);
			panel.add(buttonRemove);
			add(panel);
		}

		loadThemes();
	}

	private void displayNoRight() {
		add(new HTML("100回以上プレイされた方はテーマモードの編集が出来ます。<br>編集権限を御希望の方は100回以上プレイされた後、<br>この画面から申請してください。"));
	}

	private void displayHaveRight() {
		add(new HTML("テーマモードの編集権限の申請が出来ます。<br>編集権限を御希望の方は以下のボタンを押してください。"));

		Service.Util.getInstance().isApplyingThemeModeEditor(UserData.getInstance().getUserCode(), callbackIsApplyingThemeModeEditor);
	}

	private final AsyncCallback<Boolean> callbackIsApplyingThemeModeEditor = new AsyncCallback<Boolean>() {
		public void onSuccess(Boolean result) {
			if (result) {
				add(buttonApplication);
				buttonApplication.setText("現在申請中です。承認されるまでしばらくお待ちください。");
				buttonApplication.setEnabled(false);
			} else {
				add(new HTML("申請にあたり作りたい検定や自己アピール等をお願いいたします。"));
				textBox.setWidth("400px");
				add(textBox);
				add(buttonApplication);
			}
		}

		public void onFailure(Throwable caught) {
		}
	};

	private void loadThemes() {
		Service.Util.getInstance().getThemeModeQuery(callbackGetThemeModeQuery);
	}

	private final AsyncCallback<Map<String, List<String>>> callbackGetThemeModeQuery = new AsyncCallback<Map<String, List<String>>>() {
		public void onSuccess(Map<String, List<String>> result) {
			setGrid(result);
		}

		public void onFailure(Throwable caught) {
			caught.printStackTrace();
		}
	};

	private void setGrid(Map<String, List<String>> data) {
		grid.resize(data.size() + 1, 2);
		grid.setHTML(0, 0, "テーマ");
		grid.setHTML(0, 1, "単語");

		int row = 1;
		for (Entry<String, List<String>> entry : data.entrySet()) {
			final String theme = entry.getKey();
			final List<String> queries = entry.getValue();
			grid.setHTML(row, 0, theme);

			final FlowPanel flowPanel = new FlowPanel();
			for (final String query : queries) {
				final ClickHandler handler = new ClickHandler() {
					public void onClick(ClickEvent event) {
						textBoxTheme.setText(theme);
						textBoxQuery.setText(query);
					}
				};
				final Button button = new Button(query, handler);
				flowPanel.add(button);
				flowPanel.setWidth("400px");
			}
			grid.setWidget(row, 1, flowPanel);
			++row;
		}
	}

	public void onClick(ClickEvent event) {
		final Object source = event.getSource();
		if (source == buttonAdd) {
			final String theme = textBoxTheme.getText();
			final String query = textBoxQuery.getText();
			Service.Util.getInstance().addThemeModeQuery(theme, query, callbackUpdateThemeModeQuery);

		} else if (source == buttonRemove) {
			final String theme = textBoxTheme.getText();
			final String query = textBoxQuery.getText();
			Service.Util.getInstance().removeThemeModeQuery(theme, query, callbackUpdateThemeModeQuery);

		} else if (source == buttonApplication) {
			if (Window.confirm("テーマモードの編集権限の申請をします\nよろしいですか？")) {
				Service.Util.getInstance().applyThemeModeEditor(UserData.getInstance().getUserCode(), textBox.getText(), Service.NULL_CALLBACK);
				buttonApplication.setText("現在申請中です。承認されるまでしばらくお待ちください。");
				buttonApplication.setEnabled(false);
			}
		}
	}

	private final AsyncCallback<Void> callbackUpdateThemeModeQuery = new AsyncCallback<Void>() {
		public void onSuccess(Void result) {
			loadThemes();
		}

		public void onFailure(Throwable caught) {
			caught.printStackTrace();
		}
	};

	private void updateForm() {
		final boolean enabled = checkForm();
		buttonAdd.setEnabled(enabled);
		buttonRemove.setEnabled(enabled);
	}

	private boolean checkForm() {
		return textBoxTheme.getText().length() > 0 && textBoxQuery.getText().length() > 0;
	}

	protected void onLoad() {
		super.onLoad();
		timerUpdateForm.scheduleRepeating(UPDATE_PERIOD);
	}

	protected void onUnload() {
		timerUpdateForm.cancel();
		super.onUnload();
	}
}
